﻿namespace LogManager.Gui.ViewModels
{
    using System;
    using System.Net.Mail;
    using System.Windows.Controls;
    using System.Windows.Media;
    using LogManager.Core.Infrastructure.Logging;
    using LogManager.Core.Models;
    using LogManager.Core.Models.Smtp;
    using LogManager.Gui.Views;

    public class SettingsViewModel : ViewModelBase<ISettingsView>, ISettingsViewModel
    {
        public virtual ISettings Settings { get; set; }

        public SettingsViewModel(ISettingsView view, ISettings settings)
            : base(view)
        {
            Settings = settings;
        }

        public void OnEmailEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            var textElemnt = (TextBox)e.EditingElement;
            var oldEmail = (Email)e.Row.Item;

            if (string.IsNullOrEmpty(textElemnt.Text))
            {
                return;
            }

            MailAddress email = null;
            try
            {
                email = new MailAddress(textElemnt.Text);
                oldEmail.Value = email;
                textElemnt.Foreground = Brushes.Black;
            }
            catch (Exception ex)
            {
                textElemnt.Foreground = Brushes.Red;
                Log.Logger.AddWarning("Bad email : " + textElemnt.Text, ex.Message);
                e.Cancel = true;
            }
        }
    }
}
